package com.ruoyi.system.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.pay.MyWxMiniConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class PayUtil {

    @Autowired
    private MyWxMiniConfig myWxMiniConfig;

    /**
     * 根据jscode获取openId
     * @param jsCode
     * @return
     */
    public String getWxOpenIdByJsCode(String jsCode){
        String openid = "";
        if (StringUtils.isEmpty(jsCode)){
            return openid;
        }
        Map<String,Object> params = new HashMap<>();
        params.put("secret", myWxMiniConfig.getSecret());
        params.put("appid", myWxMiniConfig.getAppid());
        params.put("grant_type", "authorization_code");
        params.put("js_code", jsCode);
        String result = HttpUtils.sendGet("https://api.weixin.qq.com/sns/jscode2session",HttpUtils.getUrlParamsByMap(params));
        JSONObject jsonObject = JSON.parseObject(result);
        if (jsonObject!=null && jsonObject.containsKey("openid")){
            openid = jsonObject.get("openid").toString();
        }
        return openid;
    }


}
